import { Module } from "vuex";
// 该泛型需结合两个参数
import IProductState from "./type";
import { IRootState } from "@/store/types";
import {
  addCategory,
  getCategory,
  deleteCategory,
  updataCategory
} from "@/service/main/goods";
const systemModule: Module<IProductState, IRootState> = {
  // 提供一个作用域
  namespaced: true,
  state() {
    return {
      categoryList: []
    };
  },
  actions: {
    // 添加
    async addCategory({ commit, dispatch }, data) {
      let res = await addCategory(data);
      res = res.data;
      if (res.total == 200) {
        dispatch("getCategory");
        return Promise.resolve("ok");
      } else {
        return Promise.reject(new Error("fail"));
      }
    },
    // 修改
    async editCategory({ commit, dispatch }, data) {
      console.log("修改商品请求");
      let res = await updataCategory(data);
      res = res.data;
      if (res.total == 200) {
        dispatch("getCategory");
        return Promise.resolve("ok");
      } else {
        return Promise.reject(new Error("fail"));
      }
    },
    // 删除
    async deleteCategory({ dispatch }, data) {
      let res = await deleteCategory(data);
      res = res.data;
      if (res.total == 200) {
        dispatch("getCategory");
        return Promise.resolve("ok");
      } else {
        return Promise.reject(new Error("fail"));
      }
    },
    // 修改状态
    // async updataState({ commit }, category) {
    //   let res = await updataCategory(category);
    //   res = res.data;
    //   if (res.total == 200) {
    //     return Promise.resolve("ok");
    //   } else {
    //   }
    //   return Promise.reject(new Error("修改失败"));
    // },
    // 获取分类列表
    async getCategory({ commit }) {
      let res = await getCategory();
      let { data } = res.data;
      if (res.data.total == 200) {
        commit("GETCATEGORY", data);
        return Promise.resolve("ok");
      } else {
        return Promise.reject(new Error("fail"));
      }
    }
  },
  mutations: {
    // 存储商品数据
    GETCATEGORY(state, data) {
      state.categoryList = data;
    }
  },
  getters: {
    categoryList(state) {
      return state.categoryList || [];
    }
  }
};
export default systemModule;
